package com.service.test;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder;

import com.service.cache.CacheManager;
import com.service.db.DbManager;
import com.service.socket.protocol.Conversion;
import com.service.socket.protocol.Packet;
import com.service.socket.protocol.Resolver;

public class Gtest {
	

	private static int maxSize = 500000;

	private static ClientBootstrap bootstrap;

	public ScheduledExecutorService server;
	/**
	 * 用户存放活动管道
	 */
	public static Channel activeChannel = null;
	
	public static void main(String[] args) throws Exception{
		CacheManager.instance().vehicleMap.put("11160100226", DbManager.instance().dbc.initVehicle("11160100226")) ;
		//把头尾的55 手动去了
		String target = "4700B00102000111601002261005040E3613BC22440300D8E60C00000000000000009F050000010000000000000000000000000000000000E200C00C080002000000002985";
		byte[] bytes = Conversion.dataEncode(Conversion.hexStringToBytes(target.toString()));	
		Packet packet = Resolver.parsePacket(bytes);
		packet.setDeviceNo("11160100227");
		byte[] bytes2 = Conversion.dataEncode(Conversion.hexStringToBytes(packet.toString()));				
		ChannelBuffer buffer = ChannelBuffers.copiedBuffer(bytes2);			
		System.out.println("send:"+packet.toString());	
		getActiveChannel().write(buffer);
	}
	
	public static Channel getActiveChannel() throws Exception {
		if (activeChannel == null || !activeChannel.isConnected()){
			String ip = "127.0.0.1";
			int port = 8088;
			ChannelFuture f = getBootstrap().connect(new InetSocketAddress(ip, port));
			if(!f.awaitUninterruptibly().isSuccess()){
				throw new Exception("connect err" + "(ip =" + ip + " port="+port +")");
			}
			activeChannel = f.awaitUninterruptibly().getChannel();
			return activeChannel;
		}else{
			return activeChannel;
		}
	}
	
	public static ClientBootstrap getBootstrap() {
		if (bootstrap == null){
	    	NioClientSocketChannelFactory nioscf = new NioClientSocketChannelFactory(
	    			Executors.newCachedThreadPool(),
	    			Executors.newCachedThreadPool());
	    	bootstrap = new ClientBootstrap(nioscf);
			bootstrap.setOption("child.tcpNoDelay",true);	
			bootstrap.setOption("child.keepAlive", true);

			byte[] bytes={0x55};
			final ChannelBuffer buff=ChannelBuffers.copiedBuffer(bytes);
			bootstrap.getPipeline().addLast("framer", new DelimiterBasedFrameDecoder(maxSize,buff)); 
			return bootstrap;
		}
		else{
			return bootstrap;
		}
	}
	
}
